package org.abratuhi.kvngroupware.client;

import java.util.List;

import org.abratuhi.kvngroupware.gui.GUIBrainstorm;
import org.abratuhi.kvngroupware.gui.GUIChatroom;
import org.abratuhi.kvngroupware.model.Brainstorm;
import org.abratuhi.kvngroupware.model.Chatroom;
import org.abratuhi.kvngroupware.model.Joke;
import org.abratuhi.kvngroupware.model.Scenario;
import org.abratuhi.kvngroupware.model.Team;
import org.abratuhi.kvngroupware.model.User;
import org.abratuhi.kvngroupware.network.Message;
import org.jdom.Element;

public class ClientMPTUA {
	
	KVNGroupwareClient kvnclient;
	
	public ClientMPTUA(KVNGroupwareClient kvnclient){
		this.kvnclient = kvnclient;
	}
	
	public void proceedMessage(Message message){
		Element response = ((Element) message.getRoot().getChildren("response").get(0));
		String type = response.getAttributeValue("type");
		if(type.equals("application")){
			proceedApplicationMessage(message);
		}
		else if(type.equals("brainstorm")){
			proceedBrainstormMessage(message);
		}
		else if(type.equals("chatroom")){
			proceedChatroomMessage(message);
		}
	}
	
	@SuppressWarnings("unchecked")
	public void proceedApplicationMessage(Message message){
		Element response = ((Element) message.getRoot().getChildren("response").get(0));
		String type = response.getAttributeValue("type");
		String action = response.getAttributeValue("action");
		String status = response.getAttributeValue("status");

		if(type.equals("application") && status.equals("ok")){
			if(action.equals("login")){
				Element eUser = (Element) response.getChild("user");
				String userId = eUser.getAttributeValue("id");
				
				if(this.kvnclient.getUser().getId().equals(userId)){
					this.kvnclient.setUser(User.fromElement(eUser));
					this.kvnclient.setTeam(new Team(kvnclient.getUser().getTeamId()));
					this.kvnclient.guilogin.disposeJFrame();
					this.kvnclient.guimain.createJFrame();
					//this.kvnclient.guijokemanager.createJFrame();
					
					// get brainstorms
					String[] attrNames = new String[]{"type", "action", "brainstormId", "userId", "teamId", "theme"};
					String[] attrValues= new String[]{"brainstorm", "get", "", this.kvnclient.getUser().getId(), "*", "*"};
					String text = new String();
					Element[] content = new Element[0];

					Message requestBrainstormsMessage = createMessage(attrNames, attrValues, text, content);
					this.kvnclient.sendMessage(requestBrainstormsMessage);
					
					// get chatrooms
					attrNames[2] = "chatroomId";
					attrValues[0] = "chatroom";
					Message requestChatroomsMessage = createMessage(attrNames, attrValues, text, content);
					this.kvnclient.sendMessage(requestChatroomsMessage);
					
					// get scenarios
					attrNames = new String[]{"type", "action", "leagueId", "seasonId", "teamId", "scenarioId"};
					attrValues= new String[]{"application", "get_scenario", "*", "*", kvnclient.getTeam().getId(), "*"};
					text = new String();
					content = new Element[0];

					Message requestScenariosMessage = createMessage(attrNames, attrValues, text, content);
					this.kvnclient.sendMessage(requestScenariosMessage);
					
					// get jokes
					attrNames = new String[]{"type", "action", "leagueId", "seasonId", "teamId", "userId", "jokeId"};
					attrValues= new String[]{"application", "get_joke", "*", "*", kvnclient.getTeam().getId(), "*", "*"};
					text = new String();
					content = new Element[0];

					Message requestJokesMessage = createMessage(attrNames, attrValues, text, content);
					this.kvnclient.sendMessage(requestJokesMessage);
				}
			}
			else if(action.equals("create_user")){
				kvnclient.getGUIRegistration().disposeJFrame();
			}
			else if(action.equals("create_team")){
				Team team = Team.fromElement(response.getChild("team"));
				kvnclient.getGUIRegistration().addTeamEntry(team.toElement());
			}
			else if(action.equals("get_team")){
				kvnclient.getGUIRegistration().updateTeamEntries((Element[]) response.getChildren("team").toArray(new Element[response.getChildren("team").size()]));
			}
			else if(action.equals("get_joke")){
				List<Element> eJokes = response.getChildren("joke");
				for(int i=0; i<eJokes.size(); i++){
					kvnclient.addJoke(Joke.fromElement(eJokes.get(i)));
				}
				kvnclient.guijokemanager.repaint();
			}
			else if(action.equals("create_joke")){
				Joke joke = Joke.fromElement(response.getChild("joke"));
				if(joke.getTeamId().equals(kvnclient.getTeam().getId()))kvnclient.addJoke(joke);
				kvnclient.guijokemanager.repaint();
				// TODO: change implementation
				for(int i=0; i<kvnclient.getScenarioNumber(); i++) if(kvnclient.getScenario(i).getGUI() != null) kvnclient.getScenario(i).getGUI().repaint();
			}
			else if(action.equals("update_joke")){
				Joke joke = Joke.fromElement(response.getChild("joke"));
				if(joke.getTeamId().equals(kvnclient.getTeam().getId()))kvnclient.updateJoke(joke);
				kvnclient.guijokemanager.repaint();
				// TODO: change implementation
				for(int i=0; i<kvnclient.getScenarioNumber(); i++) if(kvnclient.getScenario(i).getGUI() != null) kvnclient.getScenario(i).getGUI().repaint();
			}
			else if(action.equals("get_scenario")){
				List<Element> eScenarios = response.getChildren("scenario");
				for(int i=0; i<eScenarios.size(); i++){
					kvnclient.addScenario(Scenario.fromElement(eScenarios.get(i)));
				}
				kvnclient.getGUIMain().repaint();
			}
			else if(action.equals("create_scenario")){
				Scenario scenario = Scenario.fromElement(response.getChild("scenario"));
				if(scenario.getTeamId().equals(kvnclient.getTeam().getId())) {
					kvnclient.addScenario(scenario);
					kvnclient.getGUIMain().repaint();
				}
			}
			else if(action.equals("update_scenario")){
				Scenario scenario = Scenario.fromElement(response.getChild("scenario"));
				if(scenario.getTeamId().equals(kvnclient.getTeam().getId())) {
					kvnclient.updateScenario(scenario);
					kvnclient.getScenario(scenario.getId()).getGUI().repaint();
				}
			}
			else if(action.equals("add_scenario_joke")){
				Scenario scenario = kvnclient.getScenario(response.getAttributeValue("scenarioId"));
				if(scenario != null){
					Element[] jokeIds = (Element[]) response.getChildren("joke").toArray(new Element[response.getContentSize()]);
					for(int i=0; i<jokeIds.length; i++){
						scenario.add(jokeIds[i].getAttributeValue("id"));
					}
					kvnclient.getScenario(scenario.getId()).getGUI().repaint();
				}
			}
			else if(action.equals("remove_scenario_joke")){
				Scenario scenario = kvnclient.getScenario(response.getAttributeValue("scenarioId"));
				if(scenario != null){
					Element[] jokeIds = (Element[]) response.getChildren("joke").toArray(new Element[response.getContentSize()]);
					for(int i=0; i<jokeIds.length; i++){
						scenario.remove(jokeIds[i].getAttributeValue("id"));
					}
					kvnclient.getScenario(scenario.getId()).getGUI().repaint();
				}
			}
			else if(action.equals("up_scenario_joke")){	// TODO
				
			}
			else if(action.equals("down_scenario_joke")){// TODO
				
			}
			else if(action.equals("get_brainstorm")){	// TODO
				
			}
			else if(action.equals("logout")){
				
			}
		}
	}

	@SuppressWarnings("unchecked")
	public void proceedBrainstormMessage(Message message){
		Element response = ((Element) message.getRoot().getChildren("response").get(0));
		String type = response.getAttributeValue("type");
		String action = response.getAttributeValue("action");
		String brainstormId = response.getAttributeValue("brainstormId");
		String userId = response.getAttributeValue("userId");
		String teamId = response.getAttributeValue("teamId");
		String theme = response.getAttributeValue("theme");
		String status = response.getAttributeValue("status");
		String text = response.getText();
		
		if(type.equals("brainstorm") && status.equals("ok")){
			if(action.equals("create")){
				Brainstorm nBrainstorm = new Brainstorm(brainstormId, teamId, theme);
				this.kvnclient.addBrainstorm(nBrainstorm);
				this.kvnclient.guimain.repaint();
			}
			else if(action.equals("get")){
				if(this.kvnclient.getUser().getId().equals(userId)){
					List<Element> eBrainstorms = response.getChildren("brainstorm");
					for(int i=0; i<eBrainstorms.size();i++){
						Element eBrainstorm = eBrainstorms.get(i);
						Brainstorm brainstorm = Brainstorm.fromElement(eBrainstorm);
						this.kvnclient.addBrainstorm(brainstorm);
					}
					this.kvnclient.guimain.repaint();
				}
			}
			else if(action.equals("delete")){
				this.kvnclient.removeBrainstorm(brainstormId);
				this.kvnclient.guimain.repaint();
			}
			else if(action.equals("start")){
				
			}
			else if(action.equals("stop")){
				
			}
			else if(action.equals("join")){
				String cUserId = this.kvnclient.getUser().getId();
				Brainstorm cBrainstorm = this.kvnclient.getBrainstorm(brainstormId);
				cBrainstorm.addMember(userId, "", "idle");
				if(cUserId.equals(userId)){
					GUIBrainstorm cGUIBrainstorm = new GUIBrainstorm(this.kvnclient, cBrainstorm, kvnclient.locale);
					cBrainstorm.setGUI(cGUIBrainstorm);
					cGUIBrainstorm.createJFrame();
				}
				else{
					if(cBrainstorm.containsMember(cUserId) && cBrainstorm.getGUI() != null) cBrainstorm.getGUI().repaint();
				}
			}
			else if(action.equals("leave")){
				String cUserId = this.kvnclient.getUser().getId();
				Brainstorm cBrainstorm = this.kvnclient.getBrainstorm(brainstormId);
				cBrainstorm.removeMember(userId);
				GUIBrainstorm cGUIBrainstorm = cBrainstorm.getGUI();
				if(cUserId.equals(userId)){
					cGUIBrainstorm.disposeJFrame();
				}
				else if(cBrainstorm.containsMember(cUserId) && cGUIBrainstorm != null){
					cGUIBrainstorm.repaint();
				}
				if(cBrainstorm.getMembers().size() == 0){
					kvnclient.removeBrainstorm(cBrainstorm);
					kvnclient.getGUIMain().repaint();
				}
			}
			else if(action.equals("commit")){
				Brainstorm cBrainstorm = this.kvnclient.getBrainstorm(brainstormId);
				if(cBrainstorm != null){
					String cUserId = this.kvnclient.getUser().getId();
					GUIBrainstorm cGUIBrainstorm = cBrainstorm.getGUI();
					String sheet = text;
					cBrainstorm.commitSheet(userId, sheet);
					if(cBrainstorm.containsMember(cUserId) && cGUIBrainstorm != null){
						cBrainstorm.updateSheet(cUserId, cGUIBrainstorm.textareaSheet.getText());	//prevent text-backroll to beginning of the round caused by window repaint
						cGUIBrainstorm.repaint();
					}
				}
			}
			else if(action.equals("switch")){
				Brainstorm cBrainstorm = this.kvnclient.getBrainstorm(brainstormId);
				if(cBrainstorm != null){
					//String cUserId = this.kvnclient.getUser().getId();
					GUIBrainstorm cGUIBrainstorm = cBrainstorm.getGUI();
					cBrainstorm.switchSheets();
					//if(cBrainstorm.containsMember(cUserId) && cGUIBrainstorm != null){
						cGUIBrainstorm.repaint();
					//}
				}
			}
		}
	}
	
	@SuppressWarnings("unchecked")
	public void proceedChatroomMessage(Message message){
		Element response = ((Element) message.getRoot().getChildren("response").get(0));
		String type = response.getAttributeValue("type");
		String action = response.getAttributeValue("action");
		String chatroomId = response.getAttributeValue("chatroomId");
		String userId = response.getAttributeValue("userId");
		String status = response.getAttributeValue("status");
		String text = response.getText();
		
		if(type.equals("chatroom") && status.equals("ok")){
			if(action.equals("create")){
				Chatroom nChatroom = new Chatroom(chatroomId);
				kvnclient.addChatroom(nChatroom);
				kvnclient.getGUIMain().repaint();
			}
			else if(action.equals("get")){
				if(this.kvnclient.getUser().getId().equals(userId)){
					List<Element> eChatrooms = response.getChildren("chatroom");
					for(int i=0; i<eChatrooms.size();i++){
						Element eChatroom = eChatrooms.get(i);
						Chatroom chatroom = Chatroom.fromElement(eChatroom);
						this.kvnclient.addChatroom(chatroom);
					}
					this.kvnclient.guimain.repaint();
				}
			}
			else if(action.equals("delete")){
				kvnclient.removeChatroom(chatroomId);
				kvnclient.getGUIMain().repaint();
			}
			else if(action.equals("join")){
				String cUserId = this.kvnclient.getUser().getId();
				Chatroom cChatroom = this.kvnclient.getChatroom(chatroomId);
				cChatroom.addMember(new User(userId));
				if(cUserId.equals(userId)){
					GUIChatroom cGUIChatroom = new GUIChatroom(this.kvnclient, cChatroom, kvnclient.locale);
					cChatroom.setGUI(cGUIChatroom);
					cGUIChatroom.createJFrame();
				}
				else{
					if(cChatroom.containsMember(cUserId) && cChatroom.getGUI() != null) cChatroom.getGUI().repaint();
				}
			}
			else if(action.equals("leave")){
				String cUserId = this.kvnclient.getUser().getId();
				Chatroom cChatroom = this.kvnclient.getChatroom(chatroomId);
				cChatroom.removeMember(userId);
				GUIChatroom cGUIChatroom = cChatroom.getGUI();
				if(cUserId.equals(userId)){
					cGUIChatroom.disposeJFrame();
				}
				else if(cChatroom.containsMember(cUserId) && cGUIChatroom != null){
					cGUIChatroom.repaint();
				}
				if(cChatroom.getMembers().size() == 0){
					kvnclient.removeChatroom(cChatroom);
					kvnclient.getGUIMain().repaint();
				}
			}
			else if(action.equals("send")){
				Chatroom cChatroom = this.kvnclient.getChatroom(chatroomId);
				GUIChatroom cGUIChatroom = cChatroom.getGUI();
				cGUIChatroom.textareaMessages.append("["+userId+"]: "+text+"\n");
				cGUIChatroom.repaint();
			}
		}
	}
	
	Message createMessage(String[] attrNames, String[] attrValues, String text, Element[] content){
		Element message = new Element("message");
		message.setAttribute("application", "kvngroupware");
		
		Element request = new Element("request");
		
		request.setText(text);
		
		if(attrNames!=null && attrValues!=null && attrNames.length==attrValues.length){
		for(int i=0; i<attrNames.length; i++){
			request.setAttribute(attrNames[i], attrValues[i]);
		}
		}
		
		if(content!=null){
		for(int i=0; i<content.length; i++){
			request.addContent(content[i]);
		}
		}
		
		message.addContent(request);
		
		return new Message(message);
	}
	
}
